#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''模仿DjangoAdmin'''

from crm import models
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.shortcuts import render
from django.forms import ValidationError
from django.utils.translation import ugettext as _
from django.http import Http404
from django.urls import reverse
from django.conf import settings
import os


enabled_admins = {}    # 已注册的表
'''示例:
{
    'crm': {'customer': class_CustomerAdmin,'customerfollowup': class_CustomerFollowUpAdmin},
}
'''


class BaseAdmin(object):
    '''Admin基类'''
    list_display = []    # 自定义显示列
    list_filter = []    # 自定义过滤， 例:list_filter = [('name','用户名')]
    search_fields = []    # 自定义搜索条件 例:search_fields = [('name','用户名')]
    list_per_page = 10  # 自定义每页显示多少条数据
    ordering = 'id'    # 自定义默认排序规则
    filter_horizontal = []    # 自定义多选框字段
    actions = []    # 自定义action
    readonly_fields = []    # 修改页的只读字段
    readonly_table = False    # 整表是否只读
    modelform_exclude_fields = []    # 不显示指定字段

    def delete_selected_objs(self, request, querysets):
        '''默认action,删除选中的记录'''
        if self.readonly_table:
            raise Http404('您所执行的添加操作不被允许')
        
        res_dict = {'objs': querysets,
                    'app_name': self.model._meta.app_label,
                    'table_name': self.model._meta.model_name}

        return render(request, 'my_admin/obj_delete.html', res_dict)
    delete_selected_objs.verbose_name = '删除选中数据'

    def default_form_validation(self):
        '''定制form验证'''
        pass


def register(model_class, admin_class = None):
    '''注册表以及定制化Admin到Admin'''
    app_name = model_class._meta.app_label    # 获取Model所属的app名
    model_name = model_class._meta.model_name    # 获取Model名(小写)
    if app_name not in enabled_admins:    # 判断Model所属的app名是否已被注册过
        enabled_admins[app_name] = {}

    admin_class.model = model_class    # 关联定制化Admin和Model
    if len(admin_class.actions) == 0 or admin_class.actions[0] != 'delete_selected_objs':
        admin_class.actions.insert(0,'delete_selected_objs')    # 添加默认action

    enabled_admins[app_name][model_name] = admin_class   # 注册定制化Admin



class CustomerAdmin(BaseAdmin):
    '''给Customer定制化Admin'''
    list_display = ['id','qq', 'name', 'source', 'consultant','consult_course', 'date', 'status', 'enroll']    # 显示字段
    list_filter = [('source','来源'), ('consultant','顾问'),('consult_course','咨询课程'),('status','报名状态'), ('date','日期')]    # 过滤字段
    search_fields = [('qq','qq'), ('name', '用户名')]    # 搜索条件
    list_per_page = 5    # 每页显示多少条数据
    ordering = 'id'    # 根据id字段进行排序
    filter_horizontal = ['tags',]
    actions = ['test']    # 添加自定义action
    readonly_fields = ['qq','consultant']    # 只读字段
    # readonly_table = True

    def test(self, request, querysets):
        print(querysets)
        return HttpResponse('test')
    test.verbose_name = '测试action'

    def enroll(self):
        '''自定义显示列'''
        enrollment_url = reverse('enrollment', kwargs={'customer_id': self.instance.id})
        if self.instance.status == 0:
            return '''<a href='%s'>报名新课程</a>'''%enrollment_url
        else:
            return '''<a href='%s'>点击报名</a>''' % enrollment_url

    enroll.verbose_name='报名连接'



class CustomerFollowUpAdmin(BaseAdmin):
    '''给CustomerFollow定制化Admin'''
    list_display = ['id', 'content']
    list_filter = [('customer','用户'),  ('consultant','顾问'), ('intention', '意向')]
    search_fields = [('customer__name', '用户名')]

    def default_form_validation(self):
        '''跟进记录必须是5个字符以上'''
        consultant_content = self.cleaned_data.get('content')
        if len(consultant_content) < 5:
            self.add_error('content', '必须大于5个字符')


class UserProfileAdmin(BaseAdmin):
    list_display = ['email', 'name']
    readonly_fields = ['password',]

    filter_horizontal = ['roles','permissions' ]
    modelform_exclude_fields = ['last_login',]


class CourseRecordAdmin(BaseAdmin):
    list_filter = [('from_class','班级'),]
    list_display = ['from_class', 'day_num', 'teacher', 'has_homework','homework_title','date']
    def initialize_studyrecords(self, request, querysets):
        '''初始化学员上课记录'''
        if len(querysets) > 1:
            return HttpResponse('只能同时选择一个班级')
        else:
            study_records = []
            for enroll_obj in querysets[0].from_class.enrollment_set.filter(contract_approved=1):
                study_records.append(models.StudyRecord(student=enroll_obj,
                                                        course_record=querysets[0],
                                                        attendance=0,
                                                        score=0))
            try:
                models.StudyRecord.objects.bulk_create(study_records)    # 批量创建记录
            except Exception:
                return  HttpResponse('批量初始化上课记录失败，请检查是否有已创建的记录')
        return redirect('/my_admin/crm/studyrecord?course_record=%s'%querysets[0].id)
    initialize_studyrecords.verbose_name = '初始化学员上课记录'

    actions = ['initialize_studyrecords']


class StudyRecordAdmin(BaseAdmin):
    list_display = ['student', 'course_record', 'attendance', 'score', 'date', 'homework']
    list_filter = [('course_record','上课记录'), ('attendance','出席状况'),('score','分数')]

    def homework(self):
        '''自定义显示列'''
        class_id = str(self.instance.course_record.from_class_id)
        course_id = str(self.instance.course_record_id)
        studyrecord_id = str(self.instance.id)
        data_dir = os.path.join(settings.HOMEWORK_UPLOAD_DIR, class_id, course_id, studyrecord_id)
        if os.path.exists(data_dir):
            if len(os.listdir(data_dir))>0:
                kwargs = {'class_id': class_id,
                          'course_id': course_id,
                          'studyrecord_id':studyrecord_id}
                homework_url = reverse('download_homework', kwargs=kwargs)
                return '<a href="%s">点击下载</a>'%homework_url
        return '还未提交作业'

    homework.verbose_name = '作业下载链接'


class PermissionAdmin(BaseAdmin):
    list_display = ['name', 'content']


class RoleAdmin(BaseAdmin):
    list_display = ['name']
    filter_horizontal = ['permissions','menus']


class CourseAdmin(BaseAdmin):
    list_display = ['name', 'price', 'period']


class TagAdmin(BaseAdmin):
    list_display = ['name']


class MenuAdmin(BaseAdmin):
    list_display = ['name','url_type','url_name']


class ClassListAdmin(BaseAdmin):
    list_display = ['branch', 'course', 'class_type','start_date','end_date']
    filter_horizontal = ['teachers']


class BranchAdmin(BaseAdmin):
    list_display = ['name', 'addr']


class ContractTemplateAdmin(BaseAdmin):
    list_display = ['name']


class PaymentAdmin(BaseAdmin):
    list_display = ['customer','course','amount']


class EnrollmentAdmin(BaseAdmin):
    list_display = ['customer', 'enrolled_class', 'contract_agreed','contract_approved']



register(models.Customer, CustomerAdmin)    # 注册
register(models.CustomerFollowUp, CustomerFollowUpAdmin)
register(models.UserProfile, UserProfileAdmin)
register(models.CourseRecord, CourseRecordAdmin)
register(models.StudyRecord, StudyRecordAdmin)
register(models.Permission, PermissionAdmin)
register(models.Role, RoleAdmin)
register(models.Course, CourseAdmin)
register(models.Tag, TagAdmin)
register(models.Menu, MenuAdmin)
register(models.ClassList, ClassListAdmin)
register(models.Branch, BranchAdmin)
register(models.ContractTemplate, ContractTemplateAdmin)
register(models.Payment, PaymentAdmin)
register(models.Enrollment, EnrollmentAdmin)
